package com.gientech.subject.one.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gientech.subject.one.entity.User;
import com.gientech.subject.one.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhonghui.zhou
 * @since 2022-05-29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     *
     * * 实现：CURD，查询时需要实现翻页及根据主键批量查询
     * * 查询时增加将结果缓存到 redis
     *
     *
     * * 增删改需要加入事务管理，可以通过注解或者切面
     *
     */

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping(path = "{id}")
    public User getUserInfoById(@PathVariable("id") Integer id){
        User user = iUserService.getById(id);
        return user;
    }

    /**
     * 实现对用户的新增操作
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/save",method = RequestMethod.PUT)
    public boolean saveUser(){
        User user=new User();
        user.setId(System.currentTimeMillis());
        user.setAge(33);
        user.setName("zzh");
        user.setEmail("zhonghui.zhou@gientech.com");
        boolean save = iUserService.save(user);
        return save;
    }

    /**
     * 实现对用户的删除操作
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    public boolean deleteUser(@PathVariable("id")Integer id){
        boolean b = iUserService.removeById(id);
        return b;
    }

    /**
     * 实现对用户的修改操作
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/update/{id}",method = RequestMethod.PUT)
    public boolean updateUser(@PathVariable("id")Integer id){
        User user = iUserService.getById(id);
        user.setEmail("test@email.com.cn");
        boolean b = iUserService.updateById(user);
        return b;
    }


    /**
     * 根据主健批量查询
     * @return
     */
    @RequestMapping(value = "/query/ids",method = RequestMethod.POST)
    public List<User> queryAllUsersByIds(){
        List<Long> ids= Arrays.asList(1653811637120L,1379620465207517185L,1379671277250138114L);
//        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
//        queryWrapper.in("id",ids);
        List<User> users = iUserService.listByIds(ids);
        return users;
    }

    /**
     * 根据分页进行查询
     * @return
     */
    @RequestMapping(value = "/query/limt",method = RequestMethod.GET)
    public List<User> queryByLimit(){
        LambdaQueryWrapper<User> userLambdaQueryWrapper= Wrappers.lambdaQuery();
        userLambdaQueryWrapper.like(User::getName,"z");
        Page<User> userPage=new Page<>(1,2);
        IPage<User> userIPage=iUserService.getBaseMapper().selectPage(userPage,userLambdaQueryWrapper);
        System.out.println("总页数："+userIPage.getPages());
        System.out.println("总记录数："+userIPage.getTotal());
        userIPage.getRecords().forEach(System.out::println);
        return userIPage.getRecords();
    }

    /**
     * 查询先通过redis缓存，如果缓存查不到，去查数据库
     * @return
     */
    @RequestMapping(value = "/query/cache",method = RequestMethod.GET)
    public List<User> queryUserByCache(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        boolean hasKey=redisTemplate.hasKey("user");
        if(hasKey){
            return redisTemplate.opsForList().range("user",0,-1);
        }
        List<Long> ids= Arrays.asList(1653811637120L,1379620465207517185L,1379671277250138114L);
        List<User> users = iUserService.listByIds(ids);
        if(users.size()>0){
            redisTemplate.opsForList().leftPush("user",users);
        }
        return users;
    }



}
